<?php
namespace Mouta\AmistateBundle\utils;

class SfGoogleMaps {
    CONST KEY = "ABQIAAAAb5g4iyBpfowARko3e1eBchSRUsqFTVaLXTmNZHbylFUaMBJwtBTDgRpsXyJLIiWWl1evMLqz8iYFeQ";

    public static function executeGetLocalidades($name){
          $name = urlencode($name);
          $url = "http://maps.google.com/maps/geo?output=json&oe=utf-8&q=$name&key=".self::KEY."&mapclient=jsapi&hl=es";
            $txtJson = file_get_contents($url);
            $json = json_decode($txtJson);
            $result = array();
            if(isset($json->Placemark))
            {
                foreach($json->Placemark as $place)
                {
                    $localidad = "";
                    $provincia = "";
                    
                    if(isset($place->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->LocalityName))
                        $localidad = $place->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->Locality->LocalityName;

                    if(!$localidad && isset($place->AddressDetails->Country->SubAdministrativeArea->Locality->Thoroughfare->ThoroughfareName))
                        $localidad = $place->AddressDetails->Country->SubAdministrativeArea->Locality->Thoroughfare->ThoroughfareName;
                    
                    if(!$localidad && isset($place->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->SubAdministrativeAreaName))
                        $localidad = $place->AddressDetails->Country->AdministrativeArea->SubAdministrativeArea->SubAdministrativeAreaName;

                    if(isset($place->AddressDetails->Country->Locality->LocalityName))
                        $provincia = $place->AddressDetails->Country->Locality->LocalityName;

                    if(isset($place->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName))
                        $provincia = $place->AddressDetails->Country->AdministrativeArea->AdministrativeAreaName;

                    if(!isset($place->AddressDetails->Country->CountryName))
                        continue;

                    $result[] = array(
                        'label'=>$place->address,
                        'pais'=>$place->AddressDetails->Country->CountryName,
                        'provincia'=>$provincia,
                        'localidad'=>$localidad,
                        'lattitude'=>$place->Point->coordinates[0],
                        'longitude'=>$place->Point->coordinates[1],
                      );
                }
            }
          return $result;
    }
}
?>
